package com.mvvm.start.common.mvvm.v.activity

import android.os.Build
import android.text.TextUtils
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings.LOAD_CACHE_ELSE_NETWORK
import androidx.annotation.RequiresApi
import com.mvvm.start.base.base.BaseActivity
import com.mvvm.start.base.utils.loge
import com.mvvm.start.common.databinding.ActivityWebBinding
import com.mvvm.start.common.mvvm.vm.PublicViewModle
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient

import java.io.File
import java.lang.ref.WeakReference

/**
 * @author lmy
 * @功能: 腾讯X5内核的WebViewActivity
 * @Creat 2021/7/12 1:51 下午
 * @Compony 465008238@qq.com
 */
class WebActivity : BaseActivity<PublicViewModle, ActivityWebBinding>() {
    private val APP_CACAHE_DIRNAME = "/webcache"

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initView() {

        val mTitle = intent.getStringExtra("title")
        val url = intent.getStringExtra("url")

        viewBinding.toolbarplus.apply {
            toolBarBinding.tvTitle.text = mTitle
            toolBarBinding.toolbar.setNavigationOnClickListener { finish() }
            toolBarBinding.toolbar.elevation = 0F
        }

        viewBinding.webview.apply {
            //设置setWebChromeClient对象
            webChromeClient = object : WebChromeClient() {
                override fun onReceivedTitle(view: WebView, title: String) {
                    super.onReceivedTitle(view, title)
                    viewBinding.toolbarplus.toolBarBinding.tvTitle.text =
                        if (TextUtils.isEmpty(mTitle)) title else mTitle
                }

                override fun onProgressChanged(webView: WebView, i: Int) {
                    super.onProgressChanged(webView, i)
                    if (viewBinding.webProgressbar != null) {
                        if (i == 100) {
                            viewBinding.webProgressbar.visibility = View.GONE
                        } else {
                            if (viewBinding.webProgressbar.visibility == View.GONE)
                                viewBinding.webProgressbar.visibility = View.VISIBLE
                            viewBinding.webProgressbar.progress = i
                        }
                    }
                }
            }
        }
        //声明WebSettings子类
        val webSettings = viewBinding.webview.settings
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
            // 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可
            //设置自适应屏幕，两者合用
            useWideViewPort = true //将图片调整到适合webview的大小
            loadWithOverviewMode = true // 缩放至屏幕的大小
            //缩放操作
            setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。
            builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放
            displayZoomControls = false //隐藏原生的缩放控件

            //其他细节操作
            cacheMode = LOAD_CACHE_ELSE_NETWORK //关闭webview中缓存
            allowFileAccess = true //设置可以访问文件
            javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
            loadsImagesAutomatically = true //支持自动加载图片
            defaultTextEncodingName = "utf-8" //设置编码格式
        }


        viewBinding.webview.apply {
            clearCache(true)
            clearcache()
            addJavascriptInterface(
                JavaJSInterface(
                    this@WebActivity
                ), "App"
            )
            loadUrl(url)
            //步骤3. 复写shouldOverrideUrlLoading()方法，使得打开网页时不调用系统浏览器， 而是在本WebView中显示
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    view.loadUrl(url)
                    return true
                }
            }
        }
    }

    override fun initObserve() {

    }

    override fun onDestroy() {
        super.onDestroy()
        //销毁webView解决内存泄漏
        viewBinding.webview.destroy()
    }

    internal class JavaJSInterface(context: WebActivity) {
        private val x5WebViewActivity: WeakReference<WebActivity> = WeakReference(context)

        //通过这个@JavascriptInterface转化成绑定的“App”对象下的同名函数，js代码可以直接调用
        @JavascriptInterface
        fun payResult(data: String) {
            //支付结果回调
            x5WebViewActivity.get()?.payResult(data)
        }

    }

    private fun payResult(data: String) {

    }


    private fun clearcache() {
        //清理Webview缓存数据库
        try {
            deleteDatabase("webview.db")
            deleteDatabase("webviewCache.db")
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }

        //WebView 缓存文件
        val appCacheDir = File(
            filesDir.absolutePath.toString() + APP_CACAHE_DIRNAME
        )
        val webviewCacheDir =
            File(cacheDir.absolutePath.toString() + "/webviewCache")

        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir)
        }
        //删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir)
        }
    }

    private fun deleteFile(file: File) {
        if (file.exists()) {
            if (file.isFile) {
                file.delete()
            } else if (file.isDirectory) {
                val files = file.listFiles()
                for (i in files.indices) {
                    deleteFile(files[i])
                }
            }
            file.delete()
        } else {
            "delete file no exists " + file.absolutePath.loge()
        }
    }

}